package com.info.zhiduoduo.common.utils;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

import sun.misc.BASE64Encoder;

public class ImgBase64Util {

	public static final String base64Head = "data:image/jpeg;base64,";

	// 图片转化成base64字符串
	public static String ImgToBase64(String imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
			in = new FileInputStream(imgFile);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		// BASE64Encoder encoder = new BASE64Encoder();
		return Base64.encode(data);// 返回Base64编码过的字节数组字符串
	}

	public static String getNetImgToBase64(String imageUrl) throws Exception {
		//new一个URL对象
		URL url = new URL(imageUrl);
		//打开链接
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		//设置请求方式为"GET"
		conn.setRequestMethod("GET");
		//超时响应时间为5秒
		conn.setConnectTimeout(5 * 1000);
		//通过输入流获取图片数据
		InputStream inStream = conn.getInputStream();
		//得到图片的二进制数据，以二进制封装得到数据，具有通用性
		byte[] data = readInputStream(inStream);
		BASE64Encoder encode = new BASE64Encoder();
		String s = encode.encode(data);
		return base64Head+s;
	}

	private static byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		//创建一个Buffer字符串
		byte[] buffer = new byte[1024];
		//每次读取的字符串长度，如果为-1，代表全部读取完毕
		int len = 0;
		//使用一个输入流从buffer里把数据读取出来
		while( (len=inStream.read(buffer)) != -1 ){
			//用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
			outStream.write(buffer, 0, len);
		}
		//关闭输入流
		inStream.close();
		//把outStream里的数据写入内存
		return outStream.toByteArray();
	}

	/**
	 * 从URL中读取图片,转换成流形式.
	 * @param destUrl
	 * @return
	 */
	public static InputStream saveToFile(String destUrl){

        HttpURLConnection httpUrl = null;

		URL url = null;
		InputStream in = null;
		try{
			url = new URL(destUrl);
			httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.connect();
			httpUrl.getInputStream();
			in = httpUrl.getInputStream();
			return in;
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	// base64字符串转化成图片
	public static File Base64ToImg(String imgStr, String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片
		if (imgStr == null) // 图像数据为空
			return null;
		try {
			// Base64解码
			byte[] b = Base64Decoder.decode(imgStr.getBytes(), 0,
					imgStr.length());
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			//生成2级目录  /usr/local/receiptimg/20150106
			String filepath = imgFilePath.substring(0,
					imgFilePath.lastIndexOf("/"));

			File file = new File(filepath);
			if (!file.exists()) {// 判断文件是否存在
				file.mkdirs(); // 创建文件夹
			}
			
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
			return new File(imgFilePath);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 *  base64 图片上传阿里云oss
	 *
	 * @param uploadurl
	 *         上传图片的物理路径
	 * @param imgdata
	 *         base64 图片数据
	 * @return
	 */
	public static String imgUploadOss(String bucket,String uploadurl,String imgdata){
		imgdata = imgdata.substring(imgdata.indexOf("base64,") + 7);

		String oss_object = DateUtil.getNowDateString(DateUtil.FORMAT_STYLE_8);
		String fileName = UUID.randomUUID().toString() + ".png";

		//物理地址
		String imgFilePath = uploadurl+ "/" + oss_object + "/"+ fileName;
		File file = Base64ToImg(imgdata, imgFilePath);
//		OssHelper.getInstance().putFileForBase64Img(bucket,oss_object, fileName, file);

		return  oss_object + "/" + fileName;
	}


	public static void main(String[] args) throws Exception {
		System.out.println(getNetImgToBase64("http://img.huobo666.com/170706/2c3a00021f3a40765861"));
	}
}
